package com.fw.application.controller;

import cn.hutool.core.bean.BeanUtil;
import com.fw.annotation.PrintParam;
import com.fw.system.web.model.entity.ExampleTable;
import com.fw.system.web.model.form.ExampleForm;
import com.fw.system.web.model.vo.ExampleVo;
import com.fw.system.web.service.IExampleTableService;
import com.fw.common.IdXD;
import com.fw.mes.Result;
import com.fw.utils.AuthUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

import static com.fw.mes.ResultUtils.success;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yanwei
 * @since 2020-08-05
 */
@RestController
@RequestMapping("/example")
@Api(tags = "示例api")
@CrossOrigin
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ExampleTableController {

    private  final IdXD idXD;
    private final IExampleTableService exampleTableService;
    private final AuthUtils authUtils;

    @PostMapping(value = {"save", "edit"})
    @PrintParam
    @PreAuthorize("hasRole('USER')")
    public Result saveOrEdit(@RequestBody @Valid ExampleForm exampleForm) {
        ExampleTable exampleTable = new ExampleTable();
        BeanUtil.copyProperties(exampleForm, exampleTable);
        exampleTable.setId(idXD.nextId());
        exampleTable.insert();
        return success();
    }
    @GetMapping(value = {"list"})
    public Result<List<ExampleVo>> list() {
        ExampleTable exampleTable = new ExampleTable();
        List<ExampleTable> exampleTables = exampleTable.selectAll();
        List<ExampleVo> exampleVos = exampleTables.parallelStream().map(item -> {
            ExampleVo exampleVo = new ExampleVo();
            BeanUtil.copyProperties(item,exampleVo);
            return exampleVo;
        }).collect(Collectors.toList());
        return success(exampleVos);
    }

    @GetMapping("/per")
    @PreAuthorize("hasAuthority('sss')")
    public Result per(){
        return success();
    }

    @PostMapping("/getToken/{id}")
    public Result getToken(@PathVariable String id){
        String token = authUtils.createJWT(id, null, null);
        return success(token);
    }

}

